package com.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ApplicationContext {

    private Class configClass;

    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256); //单例池
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionConcurrentHashMap = new ConcurrentHashMap<String, BeanDefinition>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public ApplicationContext(Class configClass) {
        this.configClass = configClass;

        //解析配置类
        //ComponentScan注解 -->扫描路径-->扫描注解类-->BeanDefinition-->beanDefinitionConcurrentHashMap

        scan(configClass);

        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionConcurrentHashMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if(beanDefinition.getScope().equals("singleton")){
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    public Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getClazz();
        try{
            Object instance = clazz.getDeclaredConstructor().newInstance();

            //依赖注入
            for (Field field : clazz.getDeclaredFields()) {
                if(field.isAnnotationPresent(Autowired.class)){
                    Object bean = getBean(field.getName());
                    Autowired declaredAnnotation = field.getDeclaredAnnotation(Autowired.class);
                    if(bean == null && declaredAnnotation.required()){
                        throw new NullPointerException();
                    }
                    field.setAccessible(true);
                    field.set(instance, bean);
                }
            }

            //Aware回调
            if(instance instanceof BeanNameAware){
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            //初始化前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            //初始化
            if(instance instanceof InitializingBean){
                ((InitializingBean) instance).afterPropertiesSet();
            }

            //BeanPostProcessor 初始化后
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }

            return instance;
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private void scan(Class configClass) {
        ComponentScan componentScan = (ComponentScan)configClass.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScan.value();//扫描路径
        path = path.replace(".", "/");

        // Bootstrap  --> jre/lib
        // Ext  --> jre/ext/lib
        // App  --> classpath 下的class和jar包

        ClassLoader classLoader = ApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(path);
        File file = new File(resource.getFile());
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for(File f : files){
                String fileName = f.getAbsolutePath();
                if(fileName.endsWith(".class")){
                    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                    className = className.replace("\\", ".");

                    try {
                        Class<?> clazz = classLoader.loadClass(className);
                        if(clazz.isAnnotationPresent(Component.class)){
                            //表示当亲这类是一个Bean
                            //解析类 -->BeanDefinition， 判断当前bean是单例bean，还是prototype的bean
                            //BeanDefinition

                            if(BeanPostProcessor.class.isAssignableFrom(clazz)){
                                BeanPostProcessor beanPostProcessor = (BeanPostProcessor)clazz.getDeclaredConstructor().newInstance();
                                beanPostProcessorList.add(beanPostProcessor);
                            }

                            Component componentdAnnotation = clazz.getDeclaredAnnotation(Component.class);
                            String beanName = componentdAnnotation.value();
                            if(beanName.equals("")||beanName==null){
                                beanName = clazz.getSimpleName();
                                beanName = Introspector.decapitalize(beanName);
                            }

                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setClazz(clazz);
                            if(clazz.isAnnotationPresent(Scope.class)){
                                Scope scope = clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scope.value());
                            }
                            else{
                                beanDefinition.setScope("singleton");
                            }

                            beanDefinitionConcurrentHashMap.put(beanName, beanDefinition);
                        }
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public Object getBean(String beanName){
        if(beanDefinitionConcurrentHashMap.containsKey(beanName)){
            BeanDefinition beanDefinition = beanDefinitionConcurrentHashMap.get(beanName);
            if(beanDefinition.getScope().equals("singleton")){
                Object o = singletonObjects.get(beanName);
                return o;
            }
            else{
                //创建bean对象
                Object bean = createBean(beanName, beanDefinition);
                return bean;
            }
        }
        else{
            //不存在对应的bean
            throw new NullPointerException();
        }
    }
}
